<?php
class mcz_User extends mcz_Object
{
	private $acl = array();
	protected $fields = array(
		'id'         => array('cast' => 'integer'),
		'login'      => array('cast' => 'string',
				      'notblank' => true,
				      'unique' => true,
				      'modifiers' => array('trim',
							   'nodiacritics',
							   'lowercase')),
		'password'   => array('cast' => 'string',
							  'notblank' => true),
		'email'      => array('cast' => 'string',
				      'notblank' => true,
				      'unique' => true,
				      'validators' => array('email')),
		'role_id' => array('cast' => 'integer',
						   'notblank' => true),
		'created_at' => array('cast' => 'integer',
				      'notblank' => true),
		'updated_at' => array('cast' => 'integer',
				      'notblank' => true),
		'active'     => array('cast' => 'boolean',
							  'default' => true)
	);

	public function can($doshit)
	{
		if(empty($this->acl))
		{
			$sql = '
			label from mcz_Permission
			inner join mcz_RolePermission on mcz_RolePermission.permission_id = mcz_Permission.id
			where mcz_RolePermission.role_id = ?
			';
			$res = self::dbh()->fetch($sql, array($this->role_id));
			foreach($res as $row)
			{
				$this->acl[] = $row['label'];
			}
		}

		return in_array($doshit, $this->acl);
	}

	public function setRole(mcz_Role $role)
	{
		if(empty($role->id))
		{
			$role->save();
		}
		$this->role_id = $role->id;
	}

	public static function find($id)
	{
		$res = self::dbh()->fetch('* from ' . get_class() . ' where id=?',
								  array((int)$id));
		if($res)
		{
			return new mcz_User($res[0]);
		}
		return false;
	}

	public static function findOneByLogin($login)
	{
		$res = self::dbh()->fetch('* from ' . get_class() . ' where login=?',
								  array($login));
		if($res)
		{
			return new mcz_User($res[0]);
		}
		return false;
	}

	public static function findAll()
	{
		$res = self::dbh()->fetch('* from ' . get_class());
		$objects = array();
		foreach($res as $row)
		{
			$objects[] = new mcz_User($row);
		}
		return $objects;
	}

	protected function preSave()
	{
		if(empty($this->created_at))
		{
			$this->created_at = time();
		}
		$this->updated_at = time();
	}
}